<?php

class FileOperation
{
    public static function receiveUploadFile($string)/*{{{*/
    {
        $newPath    =   self::getMd5AvatarPath($string);
        if (empty($newPath) ||  empty($_FILES['avatarImage']['tmp_name']))  return  NULL;

        if (move_uploaded_file($_FILES['avatarImage']['tmp_name'], $newPath))   return  TRUE;
        return  FALSE;
    }/*}}}*/

    public static function receiveBinaryFile($string)/*{{{*/
    {
        $newPath    =   self::getMd5AvatarPath($string);
        if (empty($newPath))    return  'No mkdir path!';

        $uploadFile =   file_get_contents('php://input');
        $fileHandle =   fopen($newPath, 'w');
        $writeFile  =   fwrite($fileHandle, $uploadFile);
        fclose($fileHandle);
        return  $writeFile;
    }/*}}}*/

    public static function checkType($binaryFile, $type = NULL)/*{{{*/
    {
        if (empty($binaryFile)) return  FALSE;
        $fileTypeInfo   =   @unpack("C2chars", $binaryFile);
        $fileTypeCode   =   intval($fileTypeInfo['chars1']. $fileTypeInfo['chars2']);

        # code MAP type /*{{{*/
        $codeMapType    =   array(
                                7790    =>  'exe',
                                7784    =>  'midi',
                                8075    =>  'zip',
                                8297    =>  'rar',
                                255216  =>  'jpg',
                                7173    =>  'gif',
                                6677    =>  'bmp',
                                13780   =>  'png',
                                255251  =>  'mp3',
                            );/*}}}*/

        if (empty($codeMapType[$fileTypeCode])) return  FALSE;
        if (empty($type))   return  $codeMapType[$fileTypeCode];

        if ($codeMapType[$fileTypeCode] ==  $type)  return  TRUE;
        return  FALSE;
    }/*}}}*/

    public static function getMd5AvatarPath($string)/*{{{*/
    {
        if (empty($string)) return  FALSE;

        $md5String  =   md5($string. AC::MD5_KEY);
        $rootDir    =   substr($md5String, -4, 2);
        $subDir     =   substr($md5String, -2, 2);
        $path       =   AC::AVATAR_IMAGE_ROOT_PATH. 'avatarImage/'. $rootDir. '/'. $subDir. '/';
        if (is_dir($path))  return  $path. $string. '.jpg';

        $dirPath    =   mkdir($path, 0777, TRUE);
        if (empty($dirPath))    return  $dirPath;

        return  $path. $string. '.jpg';
    }/*}}}*/


}

final class FOP extends FileOperation{}

